package com.zhangxin.aiInterview.manager.xfapi.websocket.llmmodel;

import com.zhangxin.aiInterview.manager.xfapi.websocket.llmmodel.factory.LLmWordsWsFactory;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket连接管理器
 * 管理用户建立的websocket连接
 */
//@Component
@Deprecated
public class LLmWsManager {
    @Resource
    private LLmWordsWsFactory lLmWordsWsFactory;
    @Value("${xunfei.llm.hostUrl}")
    public String hostUrl;
    @Value("${xunfei.apiSecret}")
    public String apiSecret;
    @Value("${xunfei.apiKey}")
    public String apiKey;

    // Key: 用户ID, Value: 单个WebSocket连接
    private static final ConcurrentHashMap<Long, WebSocket> wordsConnections = new ConcurrentHashMap<>();

    /**
     * 添加或更新连接
     * @param userId 用户唯一标识
     * @param ws WebSocket连接对象
     */
    public static void addOrUpdateConnection(Long userId, WebSocket ws) {
        // 先关闭旧连接（避免泄漏）
        WebSocket oldWs = wordsConnections.get(userId);
        if (oldWs != null) {
            oldWs.close(1000, "Connection replaced");
        }
        wordsConnections.put(userId, ws);
    }

    /**
     * 初始化websocket连接
     * @param userId
     * @throws Exception
     */
    public void init(Long userId) throws Exception {
        //获取ws消息监听器
        LLmWs llmWs = lLmWordsWsFactory.createWordsWs(userId);
        // 构建鉴权url
        String authUrl = LLmWs.getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();

        //初始化用户的websocket连接
        //lLmWs 是ws消息监听器
        WebSocket webSocket = client.newWebSocket(request, llmWs);
        //管理连接
        addOrUpdateConnection(userId, webSocket);
    }

    /**
     * 获取连接
     * @param userId
     * @return
     */
    public static WebSocket getConnection(Long userId) {
        return wordsConnections.get(userId);
    }

    /**
     * 移除连接
     * @param userId 用户ID
     */
    public static void removeConnection(Long userId) {
        WebSocket ws = wordsConnections.get(userId);
        if (ws != null) {
            ws.close(1000, "Connection removed");
        }
        wordsConnections.remove(userId);
    }
}